package com.hiray.demos.visualEffect

import android.annotation.SuppressLint
import androidx.recyclerview.widget.RecyclerView
import android.util.ArrayMap
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import com.hiray.demos.R

class MultiSelectAdapter : androidx.recyclerview.widget.RecyclerView.Adapter<MultiSelectAdapter.MultiSelectViewHolder>() {

    private var isMultiSelected = false
    private val ITEM_COUNT = 28
    private val selectMap = ArrayMap<Int, Boolean>(ITEM_COUNT)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MultiSelectViewHolder {
        return MultiSelectViewHolder(LayoutInflater.from(parent.context).inflate(
                R.layout.item_multi_select_layout, parent, false
        ))
    }

    override fun getItemCount() = ITEM_COUNT

    override fun onBindViewHolder(holder: MultiSelectViewHolder, position: Int) {
        holder.bind()
    }


    fun isMultiSelect() = isMultiSelected

    /**
     * 进入可多选状态
     */
    fun setMultiSelectReady() {
        isMultiSelected = true
        notifyDataSetChanged()
    }

    /**
     * 退出多选状态
     */
    fun cancelMultiSelect() {
        isMultiSelected = false
        notifyDataSetChanged()
    }

    fun select(position: Int) {
        selectMap[position] = true
        notifyItemChanged(position)
    }

    fun unselect(position: Int) {
        selectMap[position] = false
        notifyItemChanged(position)
    }

    fun toggle(position: Int) {
        selectMap[position] = selectMap[position]!!.not()
        notifyItemChanged(position)
    }

    inner class MultiSelectViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {

        var content: TextView = itemView.findViewById(R.id.content)
        var mask: FrameLayout = itemView.findViewById(R.id.mask)

        @SuppressLint("SetTextI18n")
        fun bind() {
            content.text = "Item $adapterPosition"
            mask.visibility = if (isMultiSelected) View.VISIBLE else View.GONE
        }

    }
}